package com.serkol.abmanager;


import com.serkol.abmanager.bean.Result;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;
import java.util.List;

@RestControllerAdvice
public class ExceptionRestControllerAdvice {
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException ex) {
        ex.printStackTrace();
        StringBuffer buffer = new StringBuffer();
        List<ObjectError> allErrors = ex.getAllErrors();
        Iterator<ObjectError> iterator = allErrors.iterator();
        while (iterator.hasNext()) {
            ObjectError next = iterator.next();
            buffer.append(next.getDefaultMessage());
            buffer.append("\n");
        }
        //  FieldError fieldError = ex.getFieldError();
        return Result.failure(buffer.toString());
    }


    @ExceptionHandler(TooManyResultsException.class)
    public Result tooManyResultsException(TooManyResultsException ex) {
        ex.printStackTrace();

        //  FieldError fieldError = ex.getFieldError();
        return Result.failure(ex.getMessage());
    }

    @ExceptionHandler(NumberFormatException.class)
    public Result numberFormatException(NumberFormatException ex) {
        ex.printStackTrace();

        //  FieldError fieldError = ex.getFieldError();
        return Result.failure(ex.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {// 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                    return Result.failure(fieldError.getDefaultMessage());
            }else{
                return Result.failure();
            }

        }else{
            return Result.failure();
        }

    }
}
